package com.yanghui.dtracing.plugin.springmvc;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class HttpResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream output;

    private PrintWriter printWriter;

    public HttpResponseWrapper(HttpServletResponse response) {
        super(response);
        output = new ByteArrayOutputStream();
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream() {
            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setWriteListener(WriteListener listener) {
            }

            @Override
            public void write(int b) throws IOException {
                output.write(b);
            }
        };
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        printWriter = new PrintWriter(output);
        return this.printWriter;
    }

    public byte[] getContent() {
        if(null != printWriter && output.size() == 0){
            this.printWriter.flush();
        }
        return output.toByteArray();
    }
}
